package com.wdc.service.impl;


import com.wdc.config.AppConfig;
import com.wdc.constants.Constants;
import com.wdc.entity.dto.TokenUserInfoDto;
import com.wdc.entity.po.UserBeautyInfo;
import com.wdc.entity.query.SimplePage;
import com.wdc.entity.query.UserBeautyInfoQuery;
import com.wdc.entity.vo.UserInfoVo;
import com.wdc.enums.BeautyAccountStatusEnum;
import com.wdc.enums.PageSize;
import com.wdc.entity.vo.PaginationResultVo;
import com.wdc.entity.po.UserInfo;
import com.wdc.entity.query.UserInfoQuery;
import com.wdc.enums.UserContactTypeEnum;
import com.wdc.enums.UserStatusEnum;
import com.wdc.exception.BusinessException;
import com.wdc.mapper.UserBeautyInfoMappers;
import com.wdc.mapper.UserInfoMappers;
import com.wdc.redis.RedisComponent;
import com.wdc.service.UserInfoService;
import com.wdc.utils.CopyTools;
import com.wdc.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author: WDC
 * @description:用户信息表Service
 * @date:2024/09/09
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {


    @Resource
    private UserInfoMappers<UserInfo, UserInfoQuery> userInfoMappers;

    @Resource
    private UserBeautyInfoMappers<UserBeautyInfo, UserBeautyInfoQuery> userBeautyInfoMappers;

    @Resource
    private AppConfig appConfig;

    @Resource
    private RedisComponent redisComponent;


    /**
     * 根据条件查询列表
     */
    public List<UserInfo> findListByParam(UserInfoQuery query) {
        return this.userInfoMappers.selectList(query);

    }

    /**
     * 根据条件查询数量
     */
    public Integer findCountByParam(UserInfoQuery query) {
        return this.userInfoMappers.selectCount(query);
    }

    /**
     * 分页查询
     */
    public PaginationResultVo<UserInfo> findListByPage(UserInfoQuery query) {
        Integer count = this.findCountByParam(query);
        Integer pageSize = query.getPageSize() == null ? PageSize.SIZE15.getSize() : query.getPageSize();
        SimplePage page = new SimplePage(query.getPageNo(), count, pageSize);
        query.setSimplePage(page);
        List<UserInfo> list = this.findListByParam(query);
        PaginationResultVo<UserInfo> result = new PaginationResultVo(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    public Integer add(UserInfo bean) {
        return this.userInfoMappers.insert(bean);
    }

    /**
     * 批量新增
     */
    public Integer addBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMappers.insertBatch(listBean);
    }

    /**
     * 批量新增或修改
     */
    public Integer addOrUpdateBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMappers.insertOrUpdateBatch(listBean);
    }

    /**
     * 根据UserId查询
     */
    public UserInfo getUserInfoByUserId(String userId) {
        return this.userInfoMappers.selectByUserId(userId);
    }

    /**
     * 根据UserId更新
     */
    public Integer updateUserInfoByUserId(UserInfo bean, String userId) {
        return this.userInfoMappers.updateByUserId(bean, userId);
    }

    /**
     * 根据UserId删除
     */
    public Integer deleteUserInfoByUserId(String userId) {
        return this.userInfoMappers.deleteByUserId(userId);
    }

    /**
     * 根据Email查询
     */
    public UserInfo getUserInfoByEmail(String email) {
        return this.userInfoMappers.selectByEmail(email);
    }

    /**
     * 根据Email更新
     */
    public Integer updateUserInfoByEmail(UserInfo bean, String email) {
        return this.userInfoMappers.updateByEmail(bean, email);
    }

    /**
     * 根据Email删除
     */
    public Integer deleteUserInfoByEmail(String email) {
        return this.userInfoMappers.deleteByEmail(email);
    }


    /**
     * 注册
     *
     * @param password
     * @param email
     * @param nickname
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String password, String email, String nickname) {
        //1.查看邮箱是否以及被注册
        UserInfo userInfo = userInfoMappers.selectByEmail(email);
        if (null != userInfo) {
            throw new BusinessException("邮箱账号已经存在");
        }
        String userId = StringTools.getUserId();
        UserBeautyInfo beautyAccount = this.userBeautyInfoMappers.selectByEmail(email);
        Boolean useBeautyAccount = null != beautyAccount && BeautyAccountStatusEnum.NO_USE.getStatus().equals(beautyAccount.getStatus());
        if (useBeautyAccount) {
            userId = UserContactTypeEnum.USER.getPrefix() + beautyAccount.getStatus();
        }
        Date curDate = new Date();
        userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickName(nickname);
        userInfo.setEmail(email);
        userInfo.setPassword(StringTools.encodeMd5(password));
        userInfo.setCreateTime(curDate);
        userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
        userInfo.setLastOffTime(curDate.getTime());

        this.userInfoMappers.insert(userInfo);

        if (useBeautyAccount) {
            UserBeautyInfo updateBeauty = new UserBeautyInfo();
            updateBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());
            this.userBeautyInfoMappers.updateById(updateBeauty, beautyAccount.getId());
        }

        //TODO 创建机器人好友


    }

    @Override
    public UserInfoVo login(String email, String password) {
        UserInfo userInfo = userInfoMappers.selectByEmail(email);
        String passwordMd5 = StringTools.encodeMd5(password);
        if (null == userInfo || !userInfo.getPassword().equals(passwordMd5)) {
            throw new BusinessException("账号或者密码不存在");
        }

        if (UserStatusEnum.DISABLE.getStatus().equals(userInfo.getStatus())) {
            throw new BusinessException("账户已禁用");
        }

        //TODO 查询我的群组
        //TODO 查询我的联系人

        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto(userInfo);


        Long lastHeartBeat = redisComponent.getUserHeartbeat(userInfo.getUserId());
        if (lastHeartBeat != null) {
            throw new BusinessException("此账号已在别处登录，请退出后在登录");
        }

        //保存登录信息到redis 中
        String token = StringTools.encodeMd5(tokenUserInfoDto.getUserId() + StringTools.getRandomString(Constants.LENGTH_20));
        tokenUserInfoDto.setToken(token);
        redisComponent.saveTokenUserInfoDto(tokenUserInfoDto);


        UserInfoVo userInfoVo = CopyTools.copy(userInfo, UserInfoVo.class);
        userInfoVo.setToken(tokenUserInfoDto.getToken());
        userInfoVo.setAdmin(tokenUserInfoDto.getAdmin());


        return userInfoVo;

    }


    public TokenUserInfoDto getTokenUserInfoDto(UserInfo userInfo) {
        TokenUserInfoDto tokenUserInfoDto = new TokenUserInfoDto();
        tokenUserInfoDto.setUserId(userInfo.getUserId());
        tokenUserInfoDto.setNickName(userInfo.getNickName());

        String adminEmails = appConfig.getAdminEmails();

        if (!StringTools.isEmpty(adminEmails) && ArrayUtils.contains(adminEmails.split(","), userInfo.getEmail())) {
            tokenUserInfoDto.setAdmin(true);

        } else {
            tokenUserInfoDto.setAdmin(false);

        }
        return tokenUserInfoDto;

    }


}